package ChatApp.ServerPart;

import javax.sql.ConnectionPoolDataSource;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Zuxs
 * Date: 4.09.12
 * Time: 21:35
 * To change this template use File | Settings | File Templates.
 */
public class Server {
    private static final int port = 6666;
    private static int backlog = 6667;
    private static UsersCeeper usersCeeper;
    public static String username;

    public static void main(String[] args) throws IOException {
//        usersCeeper = new UsersCeeper("users.data");
        ServerProvider serverProvider = new ServerProvider();
        search();
        username = args[0];
        serverProvider.runServer();
    }

    public static ArrayList<String> search() throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        String myip = inetAddress.getHostAddress();
        String ipc = myip.replace(".", ":");//because dot dont work with split
        String[] temp = ipc.split(":");
        int ips = Integer.parseInt(temp[temp.length - 1]);
        int i = 0;
        while (i - 100 != ips) {
            String addip = temp[0] + "." + temp[1] + "." + temp[2];
            System.out.println(addip);
            i++;
        }
        return new ArrayList<String>();
    }

    public static class ServerProvider {
        ServerSocket serverSocket;
        Socket socket = null;
        ObjectOutputStream objectOutputStream;
        ObjectInputStream objectInputStream;
        String message;

        ServerProvider() {
        }

        void runServer() {
            try {
                serverSocket = new ServerSocket(port);
                System.out.println("Waiting for connection");
                do {

                    socket = serverSocket.accept();
                    if (socket.getRemoteSocketAddress() != null) {
                        sendMessage("Ohoy");
                        System.out.println("Ohoy we have visitor " + socket.getInetAddress().getHostAddress());
                    }
                }
                while (true);
            } catch (IOException e) {
                System.out.println("In Out " + e);
            }
        }

        void sendMessage(String message) {
            try {
                String msg = message + ":" + username;
                objectOutputStream.writeObject(msg);
                objectOutputStream.flush();
                System.out.println(username + " > " + msg);
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
}